package cn.itsource.org.service.impl;

import cn.itsource.basic.util.MD5Utils;
import cn.itsource.basic.util.StrUtils;
import cn.itsource.org.domain.Employee;
import cn.itsource.org.mapper.EmployeeMapper;
import cn.itsource.org.service.IEmployeeService;
import cn.itsource.basic.service.impl.BaseServiceImpl;
import cn.itsource.user.domain.Logininfo;
import cn.itsource.user.mapper.LogininfoMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author mochen
 * @since 2023-01-06
 */
@Service
public class EmployeeServiceImpl extends BaseServiceImpl<Employee> implements IEmployeeService {

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public void add(Employee employee) {
        initEmployee(employee);
        Logininfo logininfo = employee2Logininfo(employee);
        logininfoMapper.save(logininfo);
        employee.setLogininfoId(logininfo.getId());
        employeeMapper.save(employee);
        super.add(employee);
    }

    private Logininfo employee2Logininfo(Employee employee) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(employee,logininfo);
        logininfo.setType(false);

        return logininfo;
    }

    private void initEmployee(Employee employee) {
        String salt = StrUtils.getComplexRandomString(32);
        employee.setSalt(salt);
        employee.setPassword(MD5Utils.encrypByMd5(employee.getPassword()) + salt);
    }
}
